package com.helloae.chap07;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;

import com.esri.arcgis.datasourcesfile.ShapefileWorkspaceFactory;
import com.esri.arcgis.geodatabase.IFeatureClass;
import com.esri.arcgis.geodatabase.IFeatureWorkspace;
import com.esri.arcgis.geodatabase.IGeoDatasetSchemaEdit;
import com.esri.arcgis.geodatabase.IGeoDatasetSchemaEditProxy;
import com.esri.arcgis.geometry.IGeographicCoordinateSystem;
import com.esri.arcgis.geometry.SpatialReferenceEnvironment;
import com.esri.arcgis.geometry.esriSRGeoCSType;
import com.esri.arcgis.system.AoInitialize;
import com.esri.arcgis.system.EngineInitializer;
import com.esri.arcgis.system.esriLicenseProductCode;

/**
 * 给没有空间参考信息的shp文件增加坐标参考空间参考（即生成.prj文件）<br>
 * 功能与ArcToolbox里的Define Projection功能相同
 * @author zhushijie
 */
public class DefineGCS {

	public static void main(String[] args) throws UnknownHostException, IOException {
		// 初始化AE许可
		EngineInitializer.initializeEngine();
		AoInitialize ao = new AoInitialize();
		ao.initialize(esriLicenseProductCode.esriLicenseProductCodeEngine);
		
		//使用ShapefileWorkspaceFactory.openFromFile的方法创建一个Workspace
		ShapefileWorkspaceFactory pWF = new ShapefileWorkspaceFactory();
		String ecliseWorkspace = System.getenv("Eclipse3.6Workspace");
		IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace) pWF
				.openFromFile(ecliseWorkspace + "HelloAE" + File.separator
						+ "DataSet" + File.separator + "chap07", 0);
		//加载输入图层
		IFeatureClass pFeatureClass = pFeatureWorkspace
				.openFeatureClass("idll");
		
		SpatialReferenceEnvironment pSpatRefFact = new SpatialReferenceEnvironment();
		IGeographicCoordinateSystem pGeogCS = pSpatRefFact.createGeographicCoordinateSystem(esriSRGeoCSType.esriSRGeoCS_NAD1927);
		
		//以前一直以为这种类型转换方式只能父类、子类之间转换，原来不是这样。
		//IFeatureClass并没有实现IGeoDatasetSchemaEdit接口，但是这里也没有问题
		IGeoDatasetSchemaEdit pGeoDatasetEdit = new IGeoDatasetSchemaEditProxy(pFeatureClass);
		
		if(pGeoDatasetEdit.isCanAlterSpatialReference()){
			//执行DefineGCS操作，生成.prj文件
			pGeoDatasetEdit.alterSpatialReference(pGeogCS);
		}
		
		ao.shutdown();
		System.out.println("Congratulations!");
	}

}
